package mongodb;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.ListCollectionsIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;

/**
 * 
 * @ClassName: DataBase 
 * @Description: TODO
 * @author: Administrator
 * @date: 2016年11月18日 下午3:52:53
 */
public class DataBase {

	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		try {
			MongoClient mc=new MongoClient("127.0.0.1",27017);
			MongoDatabase dataBase = mc.getDatabase("foobar");
			System.out.println("数据库名称:"+dataBase.getName());
			//打印出该数据库下的所有集合
			ListCollectionsIterable<Document> collections =  dataBase.listCollections();
			for (Document document : collections) {
				System.out.println("集合名称:"+document.getString("name"));
			}
			
			//获取persons集合中的数据
			MongoCollection<Document> personsDB= dataBase.getCollection("persons");
			System.out.println("persons集合中数据条数:"+personsDB.count());;
			FindIterable<Document> records = personsDB.find();
			System.out.println("序列化后的值:"+JSON.serialize(records));
			for (Document document : records) {
				System.out.println(document.toJson());
				System.out.println(document.get("name"));
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
}
